package me.hl.webresponse;

import java.util.function.Function;

/**
 * Created by haoliang on 2016/7/19.
 */
public class WebResponse<T> {

    public static final int SUCCESS = 0;
    public static final int FAIL = -1;

    private int code;
    private String error;
    private T data;

    public WebResponse() {

    }

    public static <T> WebResponse<T> success(T data) {
        WebResponse response = new WebResponse();
        response.setCode(SUCCESS);
        response.setData(data);
        return response;
    }

    public static <T> WebResponse<T> error(String errorMessage) {
        WebResponse response = new WebResponse();
        response.setCode(FAIL);
        response.setError(errorMessage);
        return response;
    }

    public static <T> WebResponse<T> asProcess(WebResponse.Procedure<T> procedure,
                                               Function<Exception, String> exceptionHandler) {
        try {
            return success(procedure.apply());
        } catch (Exception e) {
            return error(exceptionHandler.apply(e));
        }
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getError() {
        return error;
    }

    public void setError(String error) {
        this.error = error;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "WebResponse{" +
                "code=" + code +
                ", error='" + error + '\'' +
                ", data=" + data +
                '}';
    }

    @FunctionalInterface
    public interface Procedure<T> {
        T apply() throws Exception;
    }
}
